package com.pishou.code.util;



import com.pishou.URLConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownload {

	public synchronized static boolean downloadFile(String filename,File file) {
		boolean flag = false;
		InputStream in = null;
		FileOutputStream fos = null;
		try{
			URL url = new URL(filename);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			int code = conn.getResponseCode();
			System.out.println(code);
			if (code == 200){
				in = conn.getInputStream();
				fos = new FileOutputStream(file);
				int len = -1;
				byte[] buffer = new byte[1024];
				while ((len = in.read(buffer))!=-1) {
					fos.write(buffer, 0, len);
				}
				flag = true;
			}
		}catch (IOException e){
			System.out.println("下载出错");
			System.out.println(e.getMessage());
			e.printStackTrace();
			file.delete();
		}finally {
			try{
				if (in!=null){
					in.close();
				}
				if (fos!=null){
					fos.close();
				}
			}catch (IOException e){
				e.printStackTrace();
			}
		}
		return flag;
	}
}
